package com.rwx.myjetpack

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.widget.Toast
import com.rwx.myjetpack.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity(),
    LoginController.OnCheckUserNameStateResultCallback, LoginController.OnDologinStateChange {

    val binding by lazy {
        ActivityMainBinding.inflate(layoutInflater)
    }

    private val loginController by lazy {
        LoginController()
    }

    private var  isUsernameAvailable=false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(binding.root)


        initListener()
    }

    private fun initListener() {

        binding.loginBtn.setOnClickListener {
            toLogin()
        }

        binding.accountInputBox.addTextChangedListener(object :TextWatcher{
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                loginController.checkUserNameState(s.toString(),this@MainActivity)

            }

        })

    }

    private fun toLogin() {

        val account = binding.accountInputBox.text.toString()
        val password = binding.passwordInputBox.text.toString()


        if(!isUsernameAvailable){
            return
        }

        loginController.doLogin(account ,password,this)


    }

    override fun onAccountFormatError() {
        binding.textState.text="账号为空"
    }

    override fun onPasswordEmpty() {
        binding.textState.text="密码为空"
    }

    override fun onLoading() {
        binding.textState.text="登陆中..."

    }

    override fun onLoginSuccess() {
        binding.textState.text="Success"
    }

    override fun onLoginFailed() {
        binding.textState.text="Failed"
    }

    override fun onNotExit() {
        isUsernameAvailable=false
        binding.textState.text="用户名不可用"


    }

    override fun onExit() {
        isUsernameAvailable=true
    }


}